package com.test.springCloud.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.tea.TeaException;
import com.test.springCloud.mapper.UserMapper;
import com.test.springCloud.service.UploadImgService;
import com.test.springCloud.service.UserService;
import com.test.springCloud.utils.Base64ToImage;
import com.test.springCloud.utils.JwtUtil;
import com.test.springCloud.utils.ResultUtils;
import com.test.springcloud.pojo.RolePojo;
import com.test.springcloud.pojo.UserPojo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


/**
 *
 */
@Service("UserService")
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    UploadImgService imgService;
    
    final static String accessKeyId="LTAI5tRwxopJBYhJ8Bx7NUxH";
    final static String accessKeySecret="T7RGscGZj8iZcTC0lpSyZZHbj7pr68";

    /**
     * 登录
     * @param req
     * @return
     */
    public UserPojo login(JSONObject req) {

        String userName = req.getString("userName");
        String hex = req.getString("password");

        String password = DigestUtil.md5Hex(hex);

        return userMapper.login(userName, password);
    }

    /**
     * 注册
     * @param req
     * @param request
     * @return
     */
    public int register(JSONObject req, HttpServletRequest request) {

        UserPojo user = new UserPojo();
        String userName = req.getString("userName");
        //通过手机号进行验证码验证
        String password = req.getString("password");
        String nickName = req.getString("nickName");//昵称
        Integer age = req.getInteger("Age");
        String sex = req.getString("Sex");
        String address = req.getString("Address");
        String avatar = req.getString("Avatar");
        Integer account = req.getInteger("Account");
        String code = req.getString("code");//验证码
        //需要在一分钟内进行验证，否则验证码将过期
        //获取存入session中的验证码
        String vcode = (String) request.getSession().getAttribute("code");
        UserPojo userPojo = userMapper.getUserByName(userName);
        //校验失败
        if (!code.equals(vcode)){
            return 4003;
        }else if (null!=userPojo){
            return 4004;
        }else {
            //验证成功后，将数据存储到实体类中
            user.setUserName(userName);
            user.setUserPwd(password);
            user.setNickName(nickName);
            user.setAge(age);
            user.setSex(sex);
            user.setAddress(address);
            user.setAvatar(avatar);
            user.setAccount(0.0);

            return userMapper.register(user);
        }
    }

    /**
     * 发送短信的创建连接
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws Exception
     */
    public com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 阿里云短信服务配置
     * @param req
     * @return
     */
    public String send(JSONObject req,HttpServletRequest httpServletRequest)throws Exception {
        JSONObject jsonObject = new JSONObject();
        String userName = req.getString("userName");
//        java.util.List<String> args = java.util.Arrays.asList(args_);
        // 初始化 Client，采用 AK&SK 鉴权访问的方式，此方式可能会存在泄漏风险，建议使用 STS 方式。鉴权访问方式请参考：https://help.aliyun.com/document_detail/378657.html
        // 获取 AK 链接：https://usercenter.console.aliyun.com
        com.aliyun.dysmsapi20170525.Client client = createClient("LTAI5tRwxopJBYhJ8Bx7NUxH", "T7RGscGZj8iZcTC0lpSyZZHbj7pr68");
        //随机生成六位验证码
        JSONObject js = new JSONObject();
        String code = vcode();
        js.put("code", code);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("短信验证")
                .setTemplateCode("SMS_154950909")
                .setPhoneNumbers(userName)
                .setTemplateParam(JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue));
        //发送完成，将验证码存入session，以便校验
        HttpSession session = httpServletRequest.getSession();
        session.setMaxInactiveInterval(1000 * 60);//有效期为一分钟
        session.setAttribute("code", code);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        jsonObject.put("code",200);
        jsonObject.put("msg","success");
        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }
    /**
     * 忘记密码
     * 手机验证修改密码
     * @param req
     * @return
     */
    public String forget(JSONObject req,HttpServletRequest request) {

        JSONObject js = new JSONObject();
        String userName = req.getString("userName");
        //通过手机号进行验证码验证
        String password = req.getString("password");
        String code = req.getString("code");//验证码
        //需要在一分钟内进行验证，否则验证码将过期
        //获取存入session中的验证码
        String vcode = (String) request.getSession().getAttribute("code");
        //校验失败
        if (!code.equals(vcode)){
            js.put("code",4004);
            js.put("msg","验证码不正确，请重新输入！");
        }else {
            Integer size = userMapper.forget(userName, password);
            if (size>0){
               js.put("code",200);
               js.put("msg","密码修改成功！");
            }else {
                js.put("code",4005);
                js.put("msg","密码修改失败，请重新尝试！");
            }
        }
        return JSONObject.toJSONString(js,SerializerFeature.WriteMapNullValue);
    }

    /**
     * 根据名字查询用户信息
     * @param name
     * @return
     */
    public UserPojo selectUserByName(String name) {
        return  userMapper.selectUserByName(name);
    }

    /**
     * 根据角色id查询角色信息
     * @param roleId
     * @return
     */
    public RolePojo getRoleById(Integer roleId) {
        return userMapper.getRoleById(roleId);
    }

    /**
     * 更改用户基本信息
     * @param req
     * @param request
     * @return
     */
    public ResultUtils updateUserInfo(JSONObject req, HttpServletRequest request) {
        ResultUtils resultUtils = null;
        //解析token
        String token = request.getHeader("token");
        String id = JwtUtil.getUserId(token);
        //获取用户信息
        Integer userId = Integer.parseInt(id);
        UserPojo user = userMapper.getUserById(userId);
        List<UserPojo> list = new ArrayList<>();
        UserPojo userPojo = new UserPojo();
        //需要更新的数据
        String nickName = req.getString("nickName");//昵称
        if("".equals(nickName)||null==nickName){
            userPojo.setNickName(user.getNickName());
        }else {
            userPojo.setNickName(nickName);
        }
        Integer age = req.getInteger("age");//年龄
        if("".equals(age)||null==age){
            userPojo.setAge(user.getAge());
        }else {
            userPojo.setAge(age);
        }
        String sex = req.getString("sex");//性别
        if("".equals(sex)||null==sex){
            userPojo.setSex(user.getSex());
        }else {
            userPojo.setSex(sex);
        }
        String address = req.getString("address");//地址
        if("".equals(address)||null==address){
            userPojo.setAddress(user.getAddress());
        }else {
            userPojo.setAddress(address);
        }
        String avatar = req.getString("avatar");//头像
        //头像上传
        if("".equals(avatar)||null==avatar){
            userPojo.setAvatar(user.getAvatar());
        }else {
            //base64转为multipartFile文件；
            Base64ToImage bImage = new Base64ToImage();
            MultipartFile f = bImage.base64MultiFile(avatar);
            // 类型转换
            MultipartFile[] file = new MultipartFile[1];
            file[0] = f;
            // 进行图片上传
            JSONObject uploadServerImgResultObject = imgService.uploadAndStoreDefaultImgToWebIndex(file);
            // 获得上传后的路径
            Integer successCount = uploadServerImgResultObject.getInteger("successCount");
            String imgUrlArrayString = "";
            for (int i = 0; i < successCount; i++) {
                if (i != successCount - 1)
                    imgUrlArrayString += uploadServerImgResultObject.getJSONObject("data").getString("remotePicUri" + i)+ ";";
                else
                    imgUrlArrayString += uploadServerImgResultObject.getJSONObject("data").getString("remotePicUri" + i);
            }
            // 设置进入实体中
            userPojo.setAvatar(imgUrlArrayString);
        }
        list.add(userPojo);
        //更新
        Integer size = userMapper.updateUserInfo(list, userId);
        if (size>0){
            resultUtils = ResultUtils.getSuccess("success");
            resultUtils.setCode(200);
            return resultUtils;
        }else {
            resultUtils = ResultUtils.getFail("failed");
            resultUtils.setCode(4026);
            return resultUtils;
        }
    }

    /**
     * 暂行用户登录
     * @param req
     * @return
     */
    @Override
    public UserPojo logins(JSONObject req) {
        String userName = req.getString("userName");
        String hex = req.getString("password");

        String password = DigestUtil.md5Hex(hex);

        return userMapper.login(userName,password);
    }

    @Override
    public UserPojo getUserById(Integer userId) {
        UserPojo user = userMapper.getUserById(userId);
        return user;
    }

    /**
     * 生成6位随机数验证码
     * @return
     */
    public static String vcode(){
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int)(Math.random() * 9);
        }
        return vcode;

    }

}
